#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: Omar Vega Ramos
# E-mail: ovruni@riseup.net
# License: GNU GPL - GNU General Public License v3.0 or later
# http://www.gnu.org/licenses/gpl.html

from argparse import ArgumentParser
from json import loads
from os.path import isfile
from time import sleep
from urllib.parse import quote_plus
from urllib.request import urlopen

parser = ArgumentParser(description='Get the coordinates of addresses in a file.')
parser.add_argument('input', help='name of the input file')
parser.add_argument('token', help='Mapbox access token')
parser.add_argument('-o', '--output', help='name of the output file')
args = parser.parse_args()

if isfile(args.input) == False:
    exit("{}: error: the file '{}' does not exist".format(parser.prog, args.input))

if not args.token:
    exit('{}: error: access token not set'.format(parser.prog))

access_token = args.token
lines = []
query_url_format = 'https://api.tiles.mapbox.com/geocoding/v5/mapbox.places/{query}.json?access_token={token}'

with open(args.input) as f:
    for line in f:
        row = {}
        query = line.strip()
        resp = urlopen(query_url_format.format(query=quote_plus(query), token=access_token))
        json_response = loads(resp.read().decode('utf-8'))
        features = json_response['features']
        row['query'] = query

        if len(features) > 0:
            lonlat = features[0]['center']
            row['lon'] = lonlat[0]
            row['lat'] = lonlat[1]
        else:
            row['lon'] = ''
            row['lat'] = ''

        if args.output is None:
            print("\"{}\",{},{}".format(query, row['lat'], row['lon']))
        else:
            lines.append(row)

        sleep(1)

if args.output is not None:
    with open(args.output, 'w') as f:
        for line in lines:
            f.write("\"{}\",{},{}\n".format(line['query'], line['lat'], line['lon']))
